﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ERP.Common.ReflectModel;
using Microsoft.EntityFrameworkCore.Internal;

namespace ERP.Common.Utils
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    public static class ReflectHelper
    {
        /// <summary>
        /// 获取控制器相关信息
        /// </summary>
        /// <param name="baseType">所继承的基类</param>
        /// <returns></returns>
        public static List<DeriveClassModel> GetControllerInfo(Type baseType)
        {
            var aa = (from control in Assembly.GetAssembly(baseType).GetTypes()
                      where control.BaseType == baseType
                      select new DeriveClassModel()
                      {
                          DeriveClassName = control.Name.Remove(control.Name.LastIndexOf("Controller", StringComparison.Ordinal)),
                          Methods = GetMethods(control, "Task`1")
                      }).ToList();

            return aa;
        }

        /// <summary>
        /// 获取派生类中方法集合
        /// </summary>
        /// <param name="deriveClass">派生类</param>
        /// <param name="returnType">方法返回类型</param>
        /// <returns></returns>
        public static List<MethodModel> GetMethods(Type deriveClass, string returnType)
        {
            return (from method in deriveClass.GetMethods().Where(r => r.ReturnType.Name == returnType && r.Name != "TryUpdateModelAsync")
                    select new MethodModel()
                    {
                        MethodName = method.Name,
                        MethodParams = GetMehtodParameters(method)
                    }).ToList();
        }

        /// <summary>
        /// 获取方法中参数集合
        /// </summary>
        /// <param name="methodInfo">方法</param>
        /// <returns></returns>
        private static List<FormalParameter> GetMehtodParameters(MethodBase methodInfo)
        {
            return (from a in methodInfo.GetParameters()
                    select new FormalParameter
                    {
                        Arguments = a.ParameterType.ShortDisplayName() + " " + a.Name
                    }).ToList();
        }
    }

}
